#include "serial.h"

//头文件
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

struct termios newtio,oldtio;


void init_array(uchar *serial_r,uchar *serial_t)
{
	uchar i;
	for(i = 0;i < 32; i ++)
	{
		serial_r[i] = 0;
		serial_t[i] = 0;
	}
}

void  open_serial(void  )
{
	fd = open("/dev/s3c2410_serial1", O_RDWR); 
	if (-1 == fd)
	{
		printf("com1 failed\n");
		exit(-1);
	}
	else
	{
		printf("com1 successs\n");
	}
	
}


void set_serial_start(int fd)
{
	tcgetattr(fd,&oldtio);
	tcflush(fd,TCIFLUSH);
	cfsetispeed(&newtio,BAUDRATE);
	cfsetospeed(&newtio,BAUDRATE);
	newtio.c_cflag &= ~CSIZE;
	newtio.c_cflag |= CS8;   

	newtio.c_cflag &= ~PARENB;
	newtio.c_iflag &= ~INPCK;

	newtio.c_cflag &= ~CSTOPB;
	newtio.c_cc[VMIN] = 1;
	newtio.c_cc[VTIME] = 0;
	tcflush(fd,TCIFLUSH);
	if(tcsetattr(fd,TCSANOW,&newtio) != 0)
	{
		printf("setting failed\n");
	//	return 0;
	}
	else printf("setting success\n");
	

}

void set_serial_end(int fd)
{
	if(tcsetattr(fd,TCSANOW,&oldtio) != 0)
		printf("setting failed\n");
	close_serial(fd);
}

void  receive_serial(int fd)
{	
	int i;	
	//uchar c;
	uchar j;
	for(j = 0;j < 32; j++)
	{
		i = read(fd,&serial_r[j],1);
//		serial_r[j] = c;
//		write(1,&serial_r[j],1);
	}
	for(j = 0; j < 32 ; j++)
		printf("%d\n",serial_r[j]);
}

uchar check_sum(uchar *serial)
{
	uchar i;
	uchar sum;
	for(i = 0;i < 30;i ++)
	{
		sum += serial[i];
	}
	return sum;
}

int send_serial(int fd)
{
	int i;
	uchar j;
	for(j = 0;j < 32;j++)
	{
		i = write(fd,&serial_t[j],1);
		if(i == -1)
		{
			printf("send failed\n");
			return -1;
		}
		else
		{
			printf("success send\n");
			return 0;
		}
	}
}

void close_serial(int fd)
{
	close(fd);
	printf("close success\n");
}


int main(int argc,char *argv[])
{
//	init_array(serial_r,serial_t);
	open_serial();
	set_serial_start(fd);
	receive_serial(fd);
	set_serial_end(fd);
	return 0;

}
